#!/usr/bin/env python
import time
import thread
import md5
import re
import cherrypy
from cherrypy import HTTPRedirect

class Web:
	def get_with_default(dict, key, default=None):
		if dict and key and dict.has_key(key):
			return dict[key]
		else:
			return default

	def check_login(back=None):
		try:
			uid = cherrypy.session.get('uid')
			if uid and ''!=uid : return uid
		except KeyError,e:
			pass
		if not back : back = cherrypy.request.script_name+cherrypy.request.path_info
		back = '/admin/user/login?back='+back
		raise HTTPRedirect(back)
	
	get_with_default = staticmethod(get_with_default)
	check_login = staticmethod(check_login)


class Tool:
	url_head_len = len('http://')
	url_head_ignore = ['#','javascript:','mailto:']
	def md5(str):
		m = md5.new()
		m.update(str)
		return m.hexdigest()
	def new_mutex():
		return thread.allocate_lock()
	def now_tick():
		return time.time()
	def sleep(sec):
		time.sleep(sec)

	def get_url_base(url):
		if not url : return None
		if not url.find('http://')==0 : return None
		domain = url[7:]
		idx_end = domain.find('/')
		if idx_end >0 : return 'http://'+domain[0:idx_end]
		else: return 'http://'+domain
	def get_url_dir(url):
		if not url : return None
		if not url.find('http://')==0 : return None
		idx_end = url.find('?')
		if idx_end < 0 : idx_end = url.rfind('/')
		if idx_end < len('http://'): return url+'/'
		return url[0:idx_end]
	def real_url(parent_url, url):
		if not parent_url or not url : return None 
		if url.find('http://')==0 : return url
		for ign in Tool.url_head_ignore:
			if url.find(ign)==0 : return None
		if url.find('/')==0 :
			url_dir = Tool.get_url_base(parent_url)
			return url_dir+url 
		else:
			url_dir = Tool.get_url_dir(parent_url)
			return url_dir+url
		
	md5 = staticmethod(md5)
	now_tick = staticmethod(now_tick)
	sleep = staticmethod(sleep)
	new_mutex = staticmethod(new_mutex)
	get_url_base = staticmethod(get_url_base)
	get_url_dir = staticmethod(get_url_dir)
	real_url = staticmethod(real_url)

